//
//  KPShareViewController.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/3/26.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import UIKit
import TangramKit
import MonkeyKing

public enum KPShareType {
    case qq
    case qzone /// QQ 空间
    case wechat /// 微信好友
    case wechatTimeline /// 微信朋友圈
    case wechatFavorite /// 微信收藏
    case weibo /// 微博
}

// MARK: - 分享功能类
class KPShareViewController: KPBaseViewController {

    var cancelButton: KPButton!
    var rootLayout: TGLinearLayout!
    var shareInfo: MonkeyKing.Info?
    var accessToken: String?

    fileprivate var types: [KPShareType]!

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nil, bundle: nil)
        types = [.qq, .qzone, .wechat, .wechatTimeline, .wechatFavorite]
    }
    convenience init(types: [KPShareType]) {
        self.init(nibName: nil, bundle: nil)
        self.types = types

    }

    override func loadView() {
        prepareView()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    // MARK: - 创建视图
    fileprivate func prepareView() {
        let liner = TGLinearLayout.init(.vert)
        liner.backgroundColor = .white
        liner.tg_height.equal(.wrap)
        liner.tg_padding = UIEdgeInsets.init(top: 0, left: 0, bottom: iPhoneXBottomH, right: 0)
        rootLayout = liner
        view = liner

        _ = UILabel.init(text: "请选择分享平台", font: 17.font).then {
            $0.textAlignment = .center
            $0.textColor = UIColor.darkText
            $0.tg_size(width: .fill, height: 40)
            liner.addSubview($0)
        }

        let flow = TGFlowLayout.init(.vert, arrangedCount: 4)
        flow.backgroundColor = .white
        flow.tg_padding = UIEdgeInsets.init(top: 15, left: 15, bottom: 15, right: 15)
        flow.tg_space = 10
        flow.tg_gravity = TGGravity.horz.fill
        flow.tg_size(width: .fill, height: .wrap)
        liner.addSubview(flow)

        for (index, item) in types.enumerated() {
            var title = ""
            var image: UIImage?
            switch item {
            case .qq:
                title = "QQ"
                image = UIImage.init(named: "umsocial_qq")
            case .wechat:
                title = "微信"
                image = UIImage.init(named: "umsocial_wechat")
            case .wechatTimeline:
                title = "微信朋友圈"
                image = UIImage.init(named: "umsocial_wechat_timeline")
            case .wechatFavorite:
                title = "微信收藏"
                image = UIImage.init(named: "umsocial_wechat_favorite")
            case .qzone:
                title = "QQ空间"
                image = UIImage.init(named: "umsocial_qzone")
            case .weibo:
                title = "新浪微博"
                image = UIImage.init(named: "umsocial_sina")
            }

            let btn = KPButton.init(image: image, title: title, color: mainTextColor)
            btn.titleLabel?.font = 15.font
            btn.imagePosistion = .top
            btn.titleImageSpacing = 5
            btn.imageSize = 58.size
            btn.tg_height.equal(btn.tg_width)
            btn.anyData = item
            btn.addTarget(self, action: #selector(shareAction(sender:)), for: .touchUpInside)
            btn.tag = 100 + index
            flow.addSubview(btn)

        }

        cancelButton = KPButton.init(image: nil, title: "取消", color: mainTextColor).then {
            $0.backgroundColor = UIColor.Material.white
            $0.tg_width.equal(.fill)
            $0.tg_height ~= 50
            $0.addTarget(self, action: #selector(cancelAction(sender:)), for: .touchUpInside)
            liner.addSubview($0)
        }
        flow.tg_bottomBorderline = TGBorderline.init(color: UIColor.lineColor, thick: 0.5)
    }

    @objc
    fileprivate func shareAction(sender: KPButton) {

        guard let shareInfo = shareInfo else {
            makeToast(message: "请先配置分享数据！")
            return
        }

        // MARK: - 运行时绑定一个属性
        guard let type = sender.anyData as? KPShareType else {
            KPLog("获取分享失败！")
            makeToast(message: "分享类型错误！")
            return
        }
        var message: MonkeyKing.Message?
        switch type {
        case .qq:
            KPLog("QQ 分享")
            message = .qq(.friends(info: shareInfo))
        case .wechat:
            KPLog("微信分享")
            message = .weChat(.session(info: shareInfo))
        case .wechatTimeline:
            KPLog("微信朋友圈分享")
            message = .weChat(.timeline(info: shareInfo))
        case .wechatFavorite:
            KPLog("微信收藏分享")
            message = .weChat(.favorite(info: shareInfo))
        case .qzone:
            KPLog("QQ 空间分享")
            message = .qq(.zone(info: shareInfo))
        case .weibo:
            KPLog("微博分享")
            if !MonkeyKing.SupportedPlatform.weibo.isAppInstalled {
                MonkeyKing.oauth(for: .weibo) { [weak self] (info, response, error) in
                    if let accessToken = info?["access_token"] as? String {
                        self?.accessToken = accessToken
                    }
                    print("MonkeyKing.oauth info: \(String(describing: info)),response:\(response), error: \(String(describing: error))")
                }
            }
            message = .weibo(.default(info: shareInfo, accessToken: accessToken))
        }

        guard let msg = message else {
            makeToast(message: "分享类型错误！")
            return
        }
        MonkeyKing.deliver(msg) { result in
            switch result {
            case .success(let json):
                KPLog(json)
            case .failure(let error):
                KPLog(error)
            }
        }
        dismiss(animated: true, completion: nil)
    }

    @objc
    fileprivate func cancelAction(sender: KPButton) {
        KPLog("取消")
        dismiss(animated: true, completion: nil)

    }

}
